<template>
  <div class="task-list">
    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.schoolId" placeholder="选择学校" clearable>
            <el-option
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-col>
        
        <el-col :span="6">
          <el-select v-model="filters.status" placeholder="任务状态" clearable>
            <el-option label="待解决" :value="0" />
            <el-option label="已关闭" :value="1" />
            <el-option label="解决中" :value="2" />
            <el-option label="已完成" :value="3" />
          </el-select>
        </el-col>
        
        <el-col :span="6">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索关键词"
            @keyup.enter="loadTasks"
          />
        </el-col>
        
        <el-col :span="6">
          <el-button type="primary" @click="loadTasks">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 任务列表 -->
    <div class="task-list-content" v-loading="loading">
      <div v-if="tasks.length === 0" class="empty-state">
        <el-empty description="暂无任务" />
      </div>
      
      <div v-else>
        <div v-for="task in tasks" :key="task.id" class="task-item">
          <el-card class="task-card">
            <div class="task-header">
              <h3 class="task-title">{{ task.title }}</h3>
              <el-tag :type="getStatusType(task.status)">
                {{ getStatusText(task.status) }}
              </el-tag>
            </div>
            
            <div class="task-content">
              <p class="task-description">{{ task.description }}</p>
              
              <div class="task-meta">
                <span class="meta-item">
                  <el-icon><Money /></el-icon>
                  奖励：¥{{ task.reward }}
                </span>
                <span class="meta-item">
                  <el-icon><Clock /></el-icon>
                  发布时间：{{ formatTime(task.createTime) }}
                </span>
                <span v-if="task.endTime" class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  结束时间：{{ task.endTime }}
                </span>
                <span class="meta-item">
                  <el-icon><School /></el-icon>
                  学校：{{ task.schoolName || '未知' }}
                </span>
                <span v-if="task.status === 2 && task.accepterName" class="meta-item">
                  <el-icon><User /></el-icon>
                  接受者：{{ task.accepterName }}
                </span>
              </div>
            </div>
            
            <div class="task-actions">
              <el-button
                v-if="task.status === 0 && canAcceptTask(task)"
                size="small"
                type="primary"
                @click="acceptTask(task)"
              >
                接受任务
              </el-button>
              <el-button
                v-if="task.status === 0 && isMyTask(task)"
                size="small"
                type="danger"
                @click="cancelTask(task)"
              >
                取消任务
              </el-button>
              <el-button
                v-if="task.status === 2 && !isMyTask(task) && isAcceptedByMe(task)"
                size="small"
                type="success"
                @click="completeTask(task)"
              >
                完成任务
              </el-button>
              <el-button
                v-if="task.status === 3 && isMyTask(task)"
                size="small"
                type="primary"
                @click="confirmTask(task)"
              >
                确认完成
              </el-button>
              <el-button
                v-if="task.status === 2 && !isMyTask(task)"
                size="small"
                disabled
              >
                已被接受
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination" v-if="tasks.length > 0">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadTasks"
        @current-change="loadTasks"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../utils/api'

const props = defineProps({
  type: {
    type: String,
    default: 'all'
  }
})

const userStore = useUserStore()
const loading = ref(false)
const tasks = ref([])
const schools = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const filters = reactive({
  schoolId: '',
  status: '',
  keyword: ''
})

const getStatusText = (status) => {
  const statusMap = {
    0: '待解决',
    1: '已关闭',
    2: '解决中',
    3: '已完成'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'info',
    2: 'primary',
    3: 'success'
  }
  return typeMap[status] || 'info'
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

const canAcceptTask = (task) => {
  // 只有待解决状态的任务可以接受，且不是自己发布的任务
  return task.status === 0 && !isMyTask(task)
}

const isMyTask = (task) => {
  // 检查是否是当前用户发布的任务
  return userStore.userInfo && task.publisherId === userStore.userInfo.id
}

const isAcceptedByMe = (task) => {
  // 检查是否是当前用户接受的任务
  return userStore.userInfo && task.accepterId === userStore.userInfo.id
}

const loadTasks = async () => {
  loading.value = true
  try {
    let url = ''
    if (props.type === 'all') {
      url = '/user/tasks'  // 修改为正确的用户端接口
    } else if (props.type === 'published') {
      url = '/user/tasks/published'
    } else if (props.type === 'accepted') {
      url = '/user/tasks/accepted'
    }
    
    console.log('加载任务，类型:', props.type, 'URL:', url)
    console.log('筛选条件:', filters)
    
    const response = await api.get(url)
    if (response.data.code === 200) {
      let filteredTasks = response.data.data
      console.log('原始任务数量:', filteredTasks.length)
      
      // 应用筛选条件
      if (filters.status !== '') {
        filteredTasks = filteredTasks.filter(task => task.status === filters.status)
        console.log('按状态筛选后:', filteredTasks.length)
      }
      
      if (filters.schoolId !== '') {
        filteredTasks = filteredTasks.filter(task => task.schoolId === filters.schoolId)
        console.log('按学校筛选后:', filteredTasks.length)
      }
      
      if (filters.keyword) {
        const keyword = filters.keyword.toLowerCase()
        filteredTasks = filteredTasks.filter(task => 
          task.title.toLowerCase().includes(keyword) || 
          task.description.toLowerCase().includes(keyword)
        )
        console.log('按关键词筛选后:', filteredTasks.length)
      }
      
      // 过滤掉已完成的任务（status === 3）
      filteredTasks = filteredTasks.filter(task => task.status !== 3)
      console.log('最终任务数量:', filteredTasks.length)
      
      tasks.value = filteredTasks
      total.value = filteredTasks.length
    }
  } catch (error) {
    console.error('加载任务失败:', error)
    ElMessage.error('加载任务失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const response = await api.get('/auth/schools')
    if (response.data.code === 200) {
      schools.value = response.data.data
    }
  } catch (error) {
    console.error('加载学校列表失败:', error)
  }
}

const resetFilters = () => {
  filters.schoolId = ''
  filters.status = ''
  filters.keyword = ''
  loadTasks()
}


const acceptTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要接受这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.post(`/user/tasks/${task.id}/accept`)
    if (response.data.code === 200) {
      ElMessage.success('接受成功')
      loadTasks()
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('接受失败')
    }
  }
}

const cancelTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要取消这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.post(`/user/tasks/${task.id}/cancel`)
    if (response.data.code === 200) {
      ElMessage.success('取消成功')
      loadTasks()
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

const completeTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要完成这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.post(`/user/tasks/${task.id}/complete`)
    if (response.data.code === 200) {
      ElMessage.success('完成成功')
      loadTasks()
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('完成失败')
    }
  }
}

const confirmTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要确认这个任务已完成吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里可以添加确认任务的API调用
    ElMessage.success('任务已确认完成')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认失败')
    }
  }
}

onMounted(() => {
  loadTasks()
  loadSchools()
})
</script>

<style scoped>
.task-list {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.task-list-content {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.task-item {
  margin-bottom: 20px;
}

.task-card {
  transition: box-shadow 0.3s;
}

.task-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-title {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.task-content {
  margin-bottom: 15px;
}

.task-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.task-meta {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  font-size: 14px;
}

.task-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
